<template>
  <section>
    <div class="add-product-form">
      <el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="addForm.productName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="产品分类" prop="classifyId" >
          <el-select v-model="addForm.classifyId" placeholder="请选择产品分类">
          <el-option v-for="item in classify"
                     :label="item.productClassifyName"
                     :value="item.id">
          </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="主图片" prop="picture">
          <el-upload
              class="upload-demo"
              name="file"
              :action="this.$uploadURL"
              :on-remove="handleFileRemove"
              :on-success="handleFileUpload"
              :on-exceed="handleFileExceed"
              :file-list="fileList"
              :limit=5
              :multiple="true"
              accept=".jpg,.png,.gif"
              list-type="picture">
<!--              :headers="{ Authorization: 'Bearer ' + localStorage.getItem('token') }">-->
            <el-button size="small" type="primary">点击上传</el-button>
<!--            <div slot="tip" class="el-upload__tip">只能上传指定类型图片文件，且不超过500kb</div>-->
          </el-upload>

        </el-form-item>
        <el-form-item label="详情图片" prop="detailsPicture">
          <el-upload
              class="upload-demo"
              name="file"
              :action="this.$uploadURL"
              :on-remove="handleFileRemove"
              :on-success="handleFileUploadDetailsPicture"
              :on-exceed="handleFileExceed"
              :file-list="fileList"
              :limit=5
              :multiple="true"
              accept=".jpg,.png,.gif"
              list-type="picture">
<!--              :headers="{ Authorization: 'Bearer ' + localStorage.getItem('token') }">-->
            <el-button size="small" type="primary">点击上传</el-button>
<!--            <div slot="tip" class="el-upload__tip">只能上传指定类型图片文件，且不超过500kb</div>-->
          </el-upload>

        </el-form-item>
        <el-form-item label="产品库存" prop="stock">
          <el-input-number v-model="addForm.stock" auto-complete="off" :min="0" :step="1"></el-input-number>
        </el-form-item>
        <el-form-item label="产品价格" prop="price">
          <el-input-number v-model="addForm.price" auto-complete="off" :min="0.00"  :step="0.10" controls-position="right"></el-input-number>
        </el-form-item>

        <el-form-item label="成本价格" prop="costPrice">
          <el-input-number v-model="addForm.costPrice" auto-complete="off" :min="0.00"  :step="0.10" controls-position="right"></el-input-number>
        </el-form-item>
        <el-form-item label="质检书" prop="qualityCertifucate">
          <el-upload
              class="upload-demo"
              name="file"
              :action="this.$uploadURL"
              :on-remove="handleFileRemove"
              :on-success="handleFilequalityCertifucate"
              :on-exceed="handleFileExceed"
              :file-list="fileList"
              :limit=1
              accept=".jpg,.png,.gif"
              list-type="picture">
            <!--              :headers="{ Authorization: 'Bearer ' + localStorage.getItem('token') }">-->
            <el-button size="small" type="primary">点击上传</el-button>
            <!--            <div slot="tip" class="el-upload__tip">只能上传指定类型图片文件，且不超过500kb</div>-->
          </el-upload>
        </el-form-item>
        <el-form-item label="附件信息"prop="annex" >
          <el-input v-model="addForm.annex" auto-complete="off" ></el-input>
        </el-form-item>
        <el-form-item label="规格参数" prop="spec">
          <el-input v-model="addForm.spec" auto-complete="off" type="textarea" :rows="1"></el-input>
        </el-form-item>
        <el-form-item label="产品内容" prop="content">
          <el-input v-model="addForm.content" auto-complete="off"  type="textarea"
                    :rows="2"
                    placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="产品简介" prop="introduction">
          <el-input v-model="addForm.introduction" auto-complete="off"  type="textarea"
                    :rows="2"
                    placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="产品标签">
          <span v-if="addForm.label.length > 0">
    <el-tag
        v-for="(tag, index) in addForm.label"
        :key="index"
        closable
        @close="handleTagClose(index)"
    >{{ tag }}</el-tag>
  </span>
          <div v-show="showNewTagInput">
            <el-input v-model="newTagInput" placeholder="请输入新标签" @input="handleNewTagInput"></el-input>
            <el-button type="primary" @click="addTag">确认</el-button>
          </div>
          <el-button type="text" @click="toggleNewTagInput">新建标签</el-button>
        </el-form-item>

      </el-form>

        <div slot="footer" class="dialog">
          <el-button v-perm="'addproduct'" type="primary" @click.native="addSubmit" :loading="addLoading">创建产品</el-button>
        </div>
    </div>
  </section>
</template>

<script>
import util from '../../common/js/util'
//import NProgress from 'nprogress'
// import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';

export default {
  mounted() {
    this.getclassify();
  },
  data() {
    return {
      addForm: {
        id: null,
        productName: '',
        picture: [],
        classify: '',
        stockId: '',
        stock:'',
        price: '',
        UpdateTime: '',
        classifyId:'',
        state:'',
        label:[],
        tags: [],
        costPrice:'',//成本价
        spec:'',//规格
        annex:'',//附件
        qualityCertifucate:'',//质检书
        content:'',//内容
        introduction:'',//简介
        detailsPicture: [],//详情图片
      },
      addFormRules:{
        productName:[{
          required: true, message: '请输入产品名称', trigger: 'blur'
        }],
        picture:[{
          required: true, message: '请上传产品主图片', trigger: 'blur'
        }],
        detailsPicture:[{
          required: true, message: '请上传产品详情图片', trigger: 'blur'
        }],
        classifyId:[{
          required: true, message: '请选择产品分类', trigger: 'blur'
        }],
       /* picture:[{
          required: true, message: '请上传产品图片', trigger: 'blur'
        }],*/ stock:[{
          required: true, message: '请输入产品库存', trigger: 'blur'
        }], price:[{
          required: true, message: '请输入填写产品价格', trigger: 'blur'
        }], costPrice:[{
          required: true, message: '请输入产品成本价格', trigger: 'blur'
        }],
       /* qualityCertifucate:[{
          required: true, message: '请输入产品质检书', trigger: 'blur'
        }],*/
        spec:[{
          required: true, message: '请填写产品规格', trigger: 'blur'
        }],


      },

//标签
      newTagInput: '', // 新标签的输入框

      showNewTagInput: false,
      newTagConfirmed: false,

      fileList: [],
      classify:[],
    }
  },
  methods: {
//获取分类
    getclassify() {
      this.$http.get("/productClassify").then(res => {
        this.classify = res.data;
        console.log(this.classify + "数据");
      });
    },

    handleNewTagInput() {
      // 处理新标签输入字段的输入
      this.newTagInput = this.newTagInput.trim();
    },
    addTag() {
      // 处理添加新标签
      if (this.newTagInput.trim() !== '') {
        this.addForm.label.push(this.newTagInput.trim());
        this.newTagInput = ''; // 清空输入字段
        this.showNewTagInput = false; // 隐藏输入字段
        this.newTagConfirmed = true; // 标记为已确认状态
      }
    },
    handleTagClose(index) {
      // 处理删除现有标签
      this.addForm.label.splice(index, 1);
    },

    toggleNewTagInput() {
      // 切换 showNewTagInput 的值
      this.showNewTagInput = !this.showNewTagInput;
      this.newTagConfirmed = false; // 重置确认状态

      if (!this.showNewTagInput) {
        // 隐藏输入框并重置新标签输入
        this.newTagInput = '';
      } else {
        // 显示输入框并聚焦
        this.$nextTick(() => {
          this.$refs.newTagInput.focus();
        });
      }
    },


    //11.提交
    addSubmit: function () {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            let para = Object.assign({}, this.addForm);
            para.label = para.label.join(' '); // 将标签数组转换为字符串
            para.picture = para.picture.join(','); // 将标签数组转换为字符串
            para.detailsPicture = para.detailsPicture.join(','); // 将标签数组转换为字符串

            this.$http.put("/productList/addData", para).then(res => {
              if (res.data.success) {
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
                // 弹出提示，询问是否跳转到产品列表页面
                this.$confirm('产品添加成功，是否跳转到产品列表页面?', '提示', {
                  confirmButtonText: '跳转',
                  cancelButtonText: '不了,还要添加',
                  type: 'info'
                }).then(() => {
                  // 用户点击确认，执行路由跳转
                  this.$router.push('/productList');
                }).catch(() => {
                  // 用户点击取消，不执行任何操作
                  this.resetFormData();
                });
                this.$refs['addForm'].resetFields();
              } else {
                this.$message.error("系统繁忙，请稍后重试!!!【500】");
              }
            });
          });
        }
      });
    },
    resetFormData() {
      this.addForm = {
        id: null,
        productName: '',
        picture: '',
        classify: '',
        stockId: '',
        stock:'',
        price: '',
        UpdateTime: '',
        classifyId:'',
        state:'',
        label:[],
        tags: [],
        costPrice:'',
        spec:'',
        annex:'',
        qualityCertifucate:'',
        content:'',
        introduction:'',
      };
      this.showNewTagInput = false;
      this.newTagInput = '';
      this.fileList = [];
    },
    //文件删除时的回调
    handleFileRemove(file, fileList) {
      //正式删除
      var fileName = null;
      if (file.response) {  //上传图片的时候点了删除
        fileName = file.response.resultObj;
      } else {  //点击修改回显的图片，点了删除
        fileName = file.url;
      }
      //为了方便参数传递,需要转换路径写法,把/替换为_
      fileName = fileName.replaceAll("/", "_");
      //发送请求
      this.$http.delete("/minio/" + fileName).then(res => {
        if (res.data.success) {
          this.$message.success("删除成功");
          this.fileList = [];
          this.addForm.picture = "";
        } else {
          this.$message.error("删除失败");
        }
      })
    },

    //主图片上传成功之后的回调
    handleFileUpload(response) {
      if (response.success) {
        this.addForm.picture.push(response.resultObj);
      }
    },
    //详情图片上传成功
    handleFileUploadDetailsPicture(response) {
      if (response.success) {
        this.addForm.detailsPicture.push(response.resultObj);
      }
    },
    handleFilequalityCertifucate(response) {
      if (response.success) {
        this.addForm.qualityCertifucate = response.resultObj;
      }
    },
    //上传超过数量的回调
    handleFileExceed() {
      this.$message.error("不能上传多张图片");
    },
  },
}

</script>

<style scoped>
.add-product-form {
  /* 样式调整，根据需要自定义 */
  max-width: 100%;
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

</style>